'use strict';
module.exports = {
	/**
	 * XXXnameXXX
	 * @url client/pages/kh/index_userdata 前端调用的url参数地址
	 * data 请求参数
	 * @param {String} params1  参数1
	 */
	main: async (event) => {
		let {
			data = {}, userInfo, util, filterResponse, originalParam
		} = event;
		let {
			customUtil,
			uniID,
			config,
			pubFun,
			vk,
			db,
			_
		} = util;
		let {
			uid,
			todatStart
		} = data;
		let res = {
			code: 0,
			msg: "",
			todaySign: false,
			last_view: {},
			clickid: ""
		};
		res.userInfo = userInfo;
		// 业务逻辑开始-----------------------------------------------------------
		var nowtime = new Date().getTime()
		await db.collection('vk-test').add({
			tips: "执行了激活函数",
			request_id: event.originalParam.context.requestId,
			user_id: userInfo._id,
		})

		//====检查今日是否签到====
		const check_signCount = await db.collection('a_sign').where({
			user_id: userInfo._id,
			_add_time: _.gte(todatStart)
		}).count()
		if (check_signCount.total > 0) {
			res.todaySign = true
		}
		//====检查今日是否签到结束====

		//====获取用户的观看历史记录====
		const last_view = await db.collection('a_history').where({
			user_id: userInfo._id
		}).orderBy('_add_time', 'desc').limit(1).get()
		res.last_view = last_view.data[0]

		//===改变用户的会员状态
		if (userInfo.plus_type == 0) {
			console.log("用户非会员");
		}
		//判断用户的会员到期没有，到期的话就把plus_type改为0
		let plus_type = userInfo.plus_type
		let plus_expire_time = userInfo.plus_expire_time
		if (plus_expire_time < nowtime && plus_type == 1) {
			console.log("用户会员已过期，改为普通用户");
			let updateVip = await db.collection('uni-id-users').doc(userInfo._id).update({
				plus_type: 0
			})
		}


		console.log("获取用户信息11111111111111", userInfo);
		//   新增内容


		//====判断用户是否已绑定广告平台信息====
		//用户已绑定广告平台的信息，则直接返回res
		// if (userInfo.tg_pt || userInfo.clue_token) {
		// 	return res;
		// }
		if (userInfo.clickid && userInfo.reback == 0) {
			await dyxcx_callback() //抖音小程序巨量回传
		}

		//未绑定则继续执行：通过客户端IP查找jl_chudian里最后一条此IP的callback,且必须是一个小时内记录的，并通过此callback回传信息给巨量
		let ip = originalParam.context.CLIENTIP;
		let chudian_info = await db.collection('jl_chudian').where({
			ip: ip,
			time: _.gt(nowtime - 3600000)
		}).orderBy('time', 'desc').limit(1).get()
		//如果没找到该IP对应的触点信息,则直接返回res
		if (chudian_info.data.length != 1) {
			return res;
		}

		//把advertiser_id带回客户端
		res.advertiser_id = chudian_info.data[0].advertiser_id || 0;
		console.log("获取账户id", chudian_info.data);


		//用监测链接去账户id 在这里跟新绑定advertiser_id
		let bind_adid = await vk.baseDao.updateAndReturn({
			dbName: "uni-id-users",
			whereJson: {
				_id: userInfo._id
			},
			dataJson: {
				advertiser_id: res.advertiser_id
			}
		});

		//如果找到了clickid且该用户激活信息未回传，就做一次激活回传。



		// 业务逻辑结束-----------------------------------------------------------
		return res;


		//   新增内容
		async function dyxcx_callback() {
			let jlurl = "https://analytics.oceanengine.com/api/v2/conversion"
			let tthuichuan_result = await uniCloud.httpclient.request(jlurl, {
				method: 'POST',
				data: {
					"event_type": "active",
					"context": {
						"ad": {
							"callback": userInfo.clickid, //callback，填写clickid
						}
					},
					"timestamp": nowtime
				},
				contentType: 'json', // 指定以application/json发送data内的数据
				dataType: 'json' // 指定返回值为json格式，自动进行parse
			})
			let add = await db.collection('vk-test').add({
				tips: "抖音小程序激活回传analytics",
				user_id: userInfo._id,
				clickid: userInfo.clickid,
				tthuichuan_result: tthuichuan_result,
				jlurl: jlurl
			})

			let dyxcx_update_reback = await db.collection('uni-id-users').doc(userInfo._id).update({
				reback: 1,
				tg_pt: "douyin"
			})
		}
	}
}